var editor;

import {getCookie} from "./utils.js";

function bindEditor() {
    const {createEditor, createToolbar} = window.wangEditor

    const editorConfig = {
        placeholder: 'Type here...',
        onChange(editor) {
            const html = editor.getHtml()
            console.log('editor content', html)
            // 也可以同步到 <textarea>
        },
    }

    editor = createEditor({
        selector: '#editor-container',
        html: '<p><br></p>',
        config: editorConfig,
        mode: 'default', // or 'simple'
    })

    const toolbarConfig = {}

    const toolbar = createToolbar({
        editor,
        selector: '#toolbar-container',
        config: toolbarConfig,
        mode: 'default', // or 'simple'
    })

}

function submitPost() {
    $('#post-btn').click(function (event) {
        event.preventDefault()
        const title = $('#title').val()
        const category = $('#category').val()
        const content = editor.getHtml()
        const csrftoken = getCookie('csrftoken'); // 获取 CSRF Token
        if (!title.trim()) {
            alert("请输入标题");
            return;
        }

        $.ajax({
                url: '/blog/post/',
                method: 'POST',
                headers: {
                    "X-CSRFToken": csrftoken // 添加 CSRF Token 到请求头
                },
                data: {
                    title: title,
                    category: category,
                    content: content
                },
                success: function (data) {
                    if (data.code === 200) {
                        window.location.href = '/blog/detail/' + data.data.blog_id;
                    } else {
                        alert(data.errors)
                    }
                },
                error: function (xhr, status, error) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        alert("错误：" + (response.message || "提交失败"));
                    } catch (e) {
                        alert("网络异常，请重试");
                    }
                }

            }
        )
    })
}

$(document).ready(function () {
    bindEditor();
    submitPost();
});

